package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * 接收Publish的生产者生成消息的subscribe-email
 */
public class Consumer02_Subscribe_Email {
    // EMAIL队列
    private static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    // 交换机
    private static final String EXCHANGE_FANOUT_INFORM = "exchange_fanout_inform";

    public static void main(String[] args) {
        // 通过链接工程创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        try {
            connection = connectionFactory.newConnection();
            // 建立通道
            Channel channel = connection.createChannel();
            // 声明目的地
            channel.queueDeclare(QUEUE_INFORM_EMAIL, true, false, false, null);
            // 绑定交换机
            channel.exchangeDeclare(EXCHANGE_FANOUT_INFORM, BuiltinExchangeType.FANOUT);

            // 开始消费
            channel.basicConsume(QUEUE_INFORM_EMAIL,true,new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String exchange = envelope.getExchange();
                    System.out.println("exchange = " + exchange);
                    String message = new String(body, StandardCharsets.UTF_8);
                    System.out.println("收到message = " + message);
                }
            });
            System.in.read();
        } catch (TimeoutException | IOException e) {
            e.printStackTrace();
        }
    }
}
